<!--页面组件-->
<template>

  <div style="position: absolute" class="taskDetailChildModal">


<!--  任务详情  -->
    <div
      v-if="showOperatingDetailsModel"
      class="tempsstyles"
      id="divFlesh"
      ref="divFlesh"
    >
      <div
        class="taskTitle"
        @mousedown="mousedownEvent($event, 'divFlesh')"
        @mouseleave="mouseout"
        @mousemove="mousemoveEvent($event)"
        @mouseup="onmouseupEvent($event)"
      >
        <span class="title" style>任务详情</span>
        <span class="close" @click="offOperatingDetails">X</span>
      </div>
      <div id="div1"></div>
      <div style="margin-bottom: -10px; margin-top: 5px">
        <Label style="margin-left: 10px">任务状态</Label>
        <RadioGroup
          v-model="algoStatus"
          @on-change="searchAlgoStatus()"
          style="margin-top: 5px"
        >
          <Radio label="">全部</Radio>
          <Radio label="running">执行中</Radio>
          <Radio label="success">成功</Radio>
          <Radio label="fail">失败</Radio>
          <Radio label="waiting">待执行</Radio>
        </RadioGroup>
        <CButton
          color="info"
          @click="reRunPartFail()"
          style="margin-left: 218px"
          class="myCol1 listbtn system-btn-style"
        >失败重试
        </CButton>
      </div>
      <div class="body">
        <Table
          border
          :columns="column"
          :data="itemsDetail"
          class="taskTableStyle"
        >
          <template slot="nodeName" slot-scope="{ row }">
            <span style="color: #7eb8ee" @click="tableMouseEnter(row)">
              {{ row.nodeName }}
            </span>
          </template>
          <template slot="identity" slot-scope="{ row }">
            <div
              style="
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              "
              :title="row.identity"
            >
              {{ row.identity }}
            </div>
          </template>
          <template slot="action" slot-scope="{ row }">
            <CButton
              v-c-tooltip="'日志'"
              title="日志"
              variant="outline"
              color="info"
              size="sm"
              @click="getTaskDetailLog(taskId, row)"
            >
              <CIcon name="cil-bug" />
            </CButton>
          </template>
          <template slot="progress" slot-scope="{ row }">
            {{
              row.progress ? row.progress : row.status == "完成" ? "100%" : "0%"
            }}
          </template>
        </Table>
      </div>
      <div class="modal-footer">
        <!-- <CButton @click="offOperatingDetails" color="info" class="okButton">确定</CButton> -->
        <CRow style="margin-top: -9px; margin-right: -25px">
          <CCol class="footerPage">
            <span class="pageContent">
              每页
              <CSelect
                @change="getVendorId($event)"
                :options="[15, 50, 100, 300, 500, 1000]"
                v-model="pageSize"
                class="selectStyle"
              />
              条记录。第{{ this.currentPage }}页(总共{{ this.total }}页，{{
                this.allNum
              }}条记录)
            </span>
            <CPagination
              :activePage.sync="currentPage"
              :pages="total"
              align="end"
              v-if="total != 0"
            />
          </CCol>
        </CRow>
      </div>
    </div>


<!-- 任务日志 -->
    <div
      v-if="showLogDetails"
      id="kkll"
      @mousedown="mousedownEvent($event, 'kkll')"
      @mouseleave="mouseout"
      @mousemove="mousemoveEvent($event)"
      @mouseup="onmouseupEvent($event)"
      class="tempsstyles"
    >
      <div style="margin: 15px">
        <span class="logTitle" style>任务日志</span>
        <span class="close" @click="offLogDetails">X</span>
      </div>
      <div>
        <div
          class="logContent"
          style="margin: 15px; max-height: 440px; overflow-y: auto"
        >
          <div v-for="(item, index) in logArr" :key="index">
            {{ item.logConsole.toString() }}
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <CButton @click="offLogDetails" color="info" class="okButton"
          >确定</CButton
        >
      </div>
    </div>




<!--  taskParameter  -->
    <div
      v-if="showParameterDetailsModel"
      class="tempsstyles showParameterDetailsModel"
      id="kk"
    >
      <div
        style="margin: 15px"
        @mousedown="mousedownEvent($event, 'kk')"
        @mouseleave="mouseout"
        @mousemove="mousemoveEvent($event)"
        @mouseup="onmouseupEvent($event)"
      >
        <span class="parameter">参数设置</span>

        <span class="close" @click="offParameterDetails">X</span>
      </div>
      <div class="bodyStyle">
        <div style="display: flex; flex-wrap: wrap">
          <div class="inputTable">
            <span class="inputData">输入参数</span>
            <Icon
              type="md-information"
              style="font-size: 20px; color: #3c6ef0"
              @click="infomationShow('input')"
            />
            <CDataTable
              :key="itemsInputParam"
              :items="itemsInputParam"
              :fields="fields"
              class="paramTable"
              border
              :header="haveHeader"
            >
              <template #label="{ item }">
                <div>
                  <td
                    style="width: 100%; padding-left: 12px"
                    :title="`${item.type.name}${
                      item.type.plural === true || item.type.plural === 'true'
                        ? '数组'
                        : ''
                    }`"
                  >
                    {{ item.label }}
                  </td>
                </div>
              </template>
              <!-- style="width:60%" -->
              <template #value="{ item }">
                <div>
                  <td style="width: 100%; padding-left: 12px">
                    <CSelect
                      v-if="item.type.name.toLowerCase() === 'select'"
                      horizontal
                      :options="item.constraint"
                      :value.sync="item.value"
                      class="inputSelectTd inputTd2"
                      placeholder="请选择"
                      :disabled="isDisabled"
                    ></CSelect>
                    <CSelect
                      v-else-if="item.type.name.toLowerCase() === 'boolean'"
                      horizontal
                      :options="[
                        { label: '请选择', value: '' },
                        { label: '是', value: true },
                        { label: '否', value: false },
                      ]"
                      :value.sync="item.value"
                      class="inputSelectTd inputTd2"
                      :disabled="isDisabled"
                    ></CSelect>
                    <div v-else-if="item.type.name.toLowerCase() === 'dir'">
                      <template>
                        <CInput
                          v-model="item.value"
                          clearable
                          autocomplete="off"
                          class="inputTd2"
                          :disabled="isDisabled"
                          :title="item.value"
                        />
                        <CButton
                          color="info"
                          size="sm"
                          @click="browserFile(item)"
                          class="btnBrowser system-btn-style"
                          :disabled="isDisabled"
                          >...</CButton
                        >
                      </template>
                    </div>
                    <div v-else-if="item.type.name.toLowerCase() === 'file'">
                      <template horizontal>
                        <CInput
                          v-model="item.value"
                          clearable
                          autocomplete="off"
                          class="inputTd2"
                          :disabled="isDisabled"
                          :title="item.value"
                        />
                        <CButton
                          color="info"
                          size="sm"
                          @click="browserFile(item)"
                          class="btnBrowser system-btn-style"
                          :disabled="isDisabled"
                          >...</CButton
                        >
                      </template>
                    </div>
                    <div
                      v-else-if="item.type.name.toLowerCase() === 'spatialref'"
                    >
                      <template>
                        <CInput
                          v-model="item.value"
                          clearable
                          autocomplete="off"
                          class="inputTd2"
                          :disabled="isDisabled"
                          :title="item.value"
                        />
                        <CButton
                          color="info"
                          size="sm"
                          @click="browserRef(item)"
                          class="btnBrowser system-btn-style"
                          :disabled="isDisabled"
                          >...</CButton
                        >
                      </template>
                    </div>
                    <div
                      v-else-if="
                        item.type.name.toLowerCase() === 'float' ||
                        item.type.name.toLowerCase() === 'double' ||
                        item.type.name.toLowerCase() === 'int'
                      "
                      class="inputTd2"
                    >
                      <Form :model="item" :rules="ruleCustom" ref="item">
                        <FormItem
                          prop="value"
                          :rules="[
                            {
                              validator: (rule, value, callback) => {
                                let data = item;
                                if (!data.hasOwnProperty('constraint'))
                                  callback();
                                let min = data.constraint.min;
                                let max = data.constraint.max;
                                let num = parseFloat(value);
                                var reg = /-?[0-9]*\.?[0-9]+/;
                                if (new RegExp(reg).test(value) == false) {
                                  if (max == undefined) {
                                    callback('请输入' + min + '以上的值');
                                  } else
                                    callback(
                                      '请输入' + min + '-' + max + '之间的值'
                                    );
                                } else {
                                  if (max == undefined) {
                                    if (num >= min) callback();
                                    else callback('请输入' + min + '以上的值');
                                  } else {
                                    if (num >= min && num <= max) callback();
                                    else {
                                      if (max == undefined)
                                        callback('请输入' + min + '以上的值');
                                      else
                                        callback(
                                          '请输入' +
                                            min +
                                            '-' +
                                            max +
                                            '之间的值'
                                        );
                                    }
                                  }
                                }
                              },
                            },
                          ]"
                        >
                          <Input
                            v-model="item.value"
                            clearable
                            autocomplete="off"
                            placeholder="请输入数字"
                            :disabled="isDisabled"
                          />
                        </FormItem>
                      </Form>
                    </div>

                    <div
                        v-else-if="
                        item.type.name.toLowerCase() === 'base_index_select' ||
                        item.type.name.toLowerCase() === 'ref_select'||
                         item.type.name.toLowerCase() === 'dem_select'
                      "
                    >
                      <CSelect
                          horizontal
                          :options="item.constraint.values"
                          :value.sync="item.value[0]"
                          class="inputSelectTd inputTd2"
                          placeholder="请选择"
                          :disabled="isDisabled"
                      ></CSelect>
                    </div>


                    <Input
                      v-else
                      v-model="item.value"
                      clearable
                      class="inputTd2"
                      :disabled="isDisabled"
                    />
                  </td>
                </div>
              </template>
            </CDataTable>
          </div>


          <div class="outputTable">
            <span class="inputData">输出参数</span>
            <Icon
              type="md-information"
              style="font-size: 20px; color: #3c6ef0"
              @click="infomationShow('output')"
            />
            <CDataTable
              :items="itemsOutputParam"
              :fields="fields"
              class="paramTable"
              border
              :header="haveHeader"
            >
              <!-- hover -->
              <template #label="{ item }">
                <div>
                  <td
                    style="width: 100%; padding-left: 12px"
                    :title="`${item.type.name}${
                      item.type.plural === true || item.type.plural === 'true'
                        ? '数组'
                        : ''
                    }`"
                  >
                    {{ item.label }}
                  </td>
                </div>
              </template>
              <template #value="{ item }">
                <div>
                  <td style="width: 100%; padding-left: 12px">
                    <div class="inputTd1">
                      <ul>
                        <li
                          v-for="(itemsli, index) in item.value"
                          :key="index"
                          :title="itemsli"
                          class="liClass"
                        >
                          {{ itemsli }}
                        </li>
                      </ul>
                    </div>
                  </td>
                </div>
              </template>
            </CDataTable>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <CButton
          color="info"
          class="okButton system-btn-style"
          v-show="saveBtnShow"
          @click="save"
          data-permission="Btn_TaskCenter_Run"
          >保存</CButton
        >
        <CButton
          color="info"
          class="okButton system-btn-style"
          @click="updateParam"
          data-permission="Btn_TaskCenter_Up"
          >编辑</CButton
        >
        <CButton
          color="info"
          class="okButton system-btn-style"
          @click="openFileListModal(false);"
          data-permission="Btn_TaskCenter_Up"
        >
          查看文件</CButton
        >
      </div>
    </div>

    <div class="tempstyle">
      <br />
      <CButton
        v-show="operatingDetailsBtnShow"
        @click="operatingDetails"
        style="width: 40px"
        class="mainBtn"
        :class="{
          'system-btn-style': showOperatingDetailsModel,
          'cancel-btn': !showOperatingDetailsModel,
        }"
      >
        <i class="fa fa-info-circle" aria-hidden="true"></i>
        任务详情
      </CButton>
      <br />

      <br />

      <CButton
        v-show="parameterDetailsBtnShow"
        @click="parameterDetails"
        class="mainBtn"
        :class="{
          'system-btn-style': showParameterDetailsModel,
          'cancel-btn': !showParameterDetailsModel,
        }"
      >
        <i class="fa fa-check-square-o" aria-hidden="true"></i>
        参数设置
      </CButton>
      <br />

      <br />

      <!-- <CButton
          v-show="parameterDetailsBtnShow"
          @click="openParameterDetails"
          class="mainBtn"
          :class="{
          'system-btn-style': showParameterDetailsModel,
          'cancel-btn': !showParameterDetailsModel,
        }"
      >
        <i class="fa fa-check-square-o" aria-hidden="true"></i>
        影像查看
      </CButton> -->
    </div>

<!--  参数详情 -->
    <Modal
      v-model="infomationModalShow"
      draggable
      title="参数详情"
      width="800"
      :styles="modalStyle"
      footer-hide
    >
      <p slot="header">{{ paramInfomation.type }}参数详情</p>
      <pre class="info-pre">
          {{ paramInfomation.content }}
        </pre
      >
    </Modal>



<!--  文件详情  -->
    <Modal v-model="fileListModal" draggable title="文件详情" width="800">
      <p slot="header">文件详情</p>
      <div style="display: flex; justify-content: space-between">
        <span>输入参数文件</span>
        <div style="float: right">
          <span>共计 {{ inputFileList.length }} 条数据</span
          ><span style="margin-left: 10px"
            >已选中 {{ inputFileSelectNum }} 条数据</span
          >
        </div>
      </div>
      <Table
        border
        ref="selection"
        :ellipsis="true"
        :columns="getinputFileColumns"
        highlight-row
        :data="inputFileList"
        @on-select="onSelectionChange"
        @on-select-cancel="onSelectionChange"
        @on-select-all="onSelectionChange"
        @on-select-all-cancel="onSelectionChange"
        v-show="inputFileList.length > 0"
      >
        <template slot="name" slot-scope="{ row }">
          <span :title="row.path">{{ row.name }}</span>
        </template>
      </Table>
      <div style="display: flex; justify-content: space-between">
        <span>输出参数文件</span>
        <div style="float: right">
          <span>共计 {{ outputFileList.length }} 条数据</span
          ><span style="margin-left: 10px"
            >已选中 {{ outputFileSelectNum }} 条数据</span
          >
        </div>
      </div>
      <Table
        border
        ref="selection2"
        :ellipsis="true"
        :columns="getinputFileColumns"
        highlight-row
        :data="outputFileList"
        @on-select="onSelectionChange1"
        @on-select-cancel="onSelectionChange1"
        @on-select-all="onSelectionChange1"
        @on-select-all-cancel="onSelectionChange1"
        v-show="outputFileList.length > 0"
      >
        <template slot="name" slot-scope="{ row }">
          <span :title="row.path">{{ row.name }}</span>
        </template>
      </Table>
      <template #footer class="footerBtns">
        <CButton
          @click="openFileBtn"
          color="info"
          id="ok"
          class="system-btn-style"
        >
          打开</CButton
        >
      </template>
    </Modal>


<!--  任务日志  -->
    <Modal
      v-model="tasklogModal"
      draggable
      title="任务日志"
      width="800"
      class="logbody"
      :styles="modalStyle"
    >
      <div
        style="word-wrap: break-word; word-break: break-all"
        v-for="(item, index) in logList"
        :key="index"
      >
        {{ item.logConsole.toString() }}
      </div>
      <template #footer class="footerBtns">
        <CButton
          @click="tasklogOk"
          color="info"
          id="ok"
          class="system-btn-style"
        >
          确定</CButton
        >
      </template>
    </Modal>



<!-- 文件选择 -->
    <FileCatalog
      ref="refFileCatalogModal"
      v-show="fileCatalogModal"
      :modalShow="fileCatalogModal"
      @closed="fileCatalogModalClose"
      @menuOk="fileCatalogModalOk"
    >
    </FileCatalog>


<!--  选择空间参考  -->
    <SpatialReferenceManage
      ref="refSpatialRefManageModal"
      v-show="spatialRefManageModal"
      :modalShow="spatialRefManageModal"
      @closed="spatialRefManageModalClose"
      @spatialRefOk="spatialRefManageModalOk"
    >
    </SpatialReferenceManage>



  </div>
</template>
<!--js代码-->
<script>
import FileCatalog from "../jobProcess/fileCatalog";
import SpatialReferenceManage from "../jobProcess/spatialReferenceManage";

const items = [];
const data = [];

const fields = [
  //  { key: "groupName", label: "组名", _style: "width:20%" },
  { key: "label", label: "参数名称", _style: "width:15%;" },
  { key: "value", label: "参数值", _style: "width:80%;" },
];

export default {
  name: "taskDetailsChild",
  props: ["taskId","workflowId"],
  data() {
    var validateAge = (rule, value, callback) => {
      if (!Number.isInteger(+value)) {
        callback(new Error("请输入数字"));
      } else {
        callback();
      }
    };
    var validateCount = (rule, value, callback) => {
      if (!Number.isInteger(+value)) {
        callback(new Error("请输入数字"));
      } else if (Number.isInteger(+value)) {
        let num = Number(value);
        let length = value.length;
        if (length < 3) {
          callback(new Error("请输入长度为3的数字"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      inputFileSelectNum: 0,
      outputFileSelectNum: 0,
      inputFileList: [],
      outputFileList: [],
      fileListModal: false,
      infoJson: {},
      infomationModalShow: false,
      paramInfomation: {
        type: "输入",
        content: {},
      },
      getinputFileColumns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          key: "name",
          slot: "name",
          title: "文件名称",
          align: "center",
        },
      ],
      column: [
        {
          key: "identity",
          slot: "identity",
          title: "影像",
          align: "center",
        },
        {
          key: "startTime",
          title: "开始时间",
          align: "center",
          width: "150",
        },
        {
          key: "endTime",
          title: "结束时间",
          align: "center",
          width: "150",
        },
        {
          key: "progress",
          slot: "progress",
          title: "进度",
          align: "center",
          width: "80",
        },
        {
          key: "status",
          title: "状态",
          align: "center",
          width: "130",
        },
        {
          key: "nodeName",
          title: "计算节点",
          slot: "nodeName",
          align: "center",
          width: "100",
        },
        {
          title: "操作",
          width: "80",
          slot: "action",
          align: "center",
        },
      ],
      modalStyle: { top: "200px" },
      operatingDetailsBtnShow: false,
      parameterDetailsBtnShow: false,

      saveBtnShow: false,
      haveHeader: false,
      currentPage: 1, //当前页面
      pages: 0,
      total: 0,
      allNum: 0,
      pageSize: 15, //每一个页面的大小
      isDisabled: true,

      data,
      algoStatus: "", //获取要搜索的算法运行状态
      algoStatusFlag: false, //记录使用那种搜索方式
      tasklogModal: false,
      show_log: false,
      mode: [{ variant: "3d" }],
      colors: ["success"],

      itemsInputParam: [],
      itemsOutputParam: [],

      logConsole: "",

      showOperatingDetailsModel: false,
      showParameterDetailsModel: false,
      showLogDetails: false,
      taskStatus: "",
      fields,
      items,

      logList: [],
      logArr: [],
      itemsDetail: [], //记录后台返回的任务条数
      itemsSearched: [], //记录查询到的数据

      //---文件目录浏览属性---
      currentItem: "",
      fileCatalogModal: false,
      spatialRefManageModal: false,
      isBatch: true,
      //---文件目录浏览属性---
      timer: null,

      drag: {}, //拖拽目标对象
      diffX: "", //拖拽位置
      diffY: "", //拖拽位置
      timeout: "",

      validateCount: validateCount,
      ruleCustom: {
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" },
          { validator: validateAge, trigger: "blur" },
        ],
        count: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          { validator: validateCount, trigger: "blur" },
        ],
        default: [
          { required: true, message: "请输入数字", trigger: "blur" },
          { validator: validateCount, trigger: "blur" },
        ],
      },





    };
  },
  created() {},
  mounted() {},
  watch: {
    pageSize(newVal, oldVal) {
      this.pageSize = newVal;
      if (this.algoStatusFlag == false) {
        this.searchAlgoStatus();
      } else {
        this.getTaskjobData(this.taskId);
      }
    },
    currentPage(newVal, oldVal) {
      this.currentPage = newVal;
      if (this.algoStatusFlag == false) {
        this.searchAlgoStatus();
      } else {
        this.getTaskjobData(this.taskId);
      }
    },
    //没用到
    // taskStatus(newVal, oldVal) {
    //   this.taskStatus = newVal;
    //   this.searchMassage();
    // },
    taskId(val) {
      if (val == "undefined") {
        this.operatingDetailsBtnShow = false;
        this.parameterDetailsBtnShow = false;

        this.showOperatingDetailsModel = false;
        this.showParameterDetailsModel = false;
      } else {
        this.operatingDetailsBtnShow = true;
        this.parameterDetailsBtnShow = true;

        this.showParameterDetailsModel = false;

        this.algoStatusFlag = false;
        this.algoStatus = "";
        this.getTaskjobData(val); //任务详情
        // this.getData(val);//参数设置
      }
    },

    itemsInputParam: {
      handler(newval, oldval) {},
      deep: true,
    },
    showOperatingDetailsModel(newVal, oldVal) {
      if (newVal == true) {
        this.timerStart();
      } else {
        this.destroyed();
      }
    },
  },
  methods: {

    //部分失败重试
    reRunPartFail(){
      let path = this.$api.taskManageApi.reRunWorkflow;
      let param = {
        reRunFromTaskId: this.taskId,
        reRunFromWorkflowId: this.workflowId,
        tryFailedJob: true,
      }
      this.http.post(path,param).then((res)=>{
        if(res.data.code == 0){
          this.$Message.success("重试成功！");
        }else{
          this.$Message.error("重试失败！");
        }
      })
    },

    //节点点击
    tableMouseEnter(row) {
      // if (row.status == "成功") {
        this.$router.push({
          path: "/monitor/statusMonitor/nodesMonitorDetail",
          query: {
            nodeName: row.nodeName,
          },
        });
      // } else {
      //   this.$Message.error("已离线 状态下暂无详情");
      // }
    },
    //搜索算法运行状态   -----新增
    //由于v-modal双向绑定，所以已获取到了radio里的状态值
    searchAlgoStatus() {
      this.algoStatusFlag = true;
      let self = this;
      let param = {
        jobStatusCode: this.algoStatus,
        workflowTaskId: this.taskId,
      };
      let path =
        this.$api.taskManageApi.queryAlgoRunningStatus +
        self.currentPage +
        "/" +
        self.pageSize;
      this.http.post(path, param).then((res) => {
        if (res.data.code == 0) {
          let data = res.data.data.list;
          if (data.length == 0) {
            this.itemsDetail = []; //未搜索到数据
          } else {
            let getData = []; //记录查询到的所有数据
            for (var i = 0; i < data.length; i++) {
              let temp = {}; //temp记录每一行的数据
              temp.name = data[i].workflowTaskName;
              //时间截取 去掉年份
              let createT = data[i].startTime;
              let endT = data[i].endTime;
              temp.startTime = createT.substring(5, createT.length);
              temp.endTime = endT.substring(5, endT.length);

              temp.algJobId = data[i].jobId;
              temp.status = data[i].status;
              temp.nodeName = data[i].nodeName;
              temp.identity = data[i].identity;
              temp.progress = data[i].progress;
              getData.push(temp); //每一行执行操作后房间getData里
            }
            this.itemsDetail = getData;
            self.allNum = res.data.data.total;
            self.total = Math.ceil(res.data.data.total / self.pageSize);
          }
        }
      });
    },
    onSelectionChange(items) {
      this.inputFileSelectNum = items.length;
    },
    onSelectionChange1(items) {
      this.outputFileSelectNum = items.length;
    },
    openFileBtn() {
      let _this = this;
      let output = this.$refs.selection2.getSelection();
      let input = this.$refs.selection.getSelection();
      let result = [];
      result = [...input, ...output];

      let files = [];
      result.forEach((element) => {
        files.push(element.path);
      });

      if (files.length < 1) {
        _this.$Message.warning("请选择要打开的文件");
      } else {
        _this.fileListModal = false;
        let url = "OpenFile://" + files.join(",");
        window.location.href = url;
      }
    },


    openFileListModal(data) {
      let _this = this;
      if (!data) {
        _this.fileListModal = true;
      }

      let inputFileArr = this.itemsInputParam.filter(
        (ele) => ele.type.name === "file" || ele.type.name === "dir"
      );
      let resultInpurList = [];
      let resultoutputList = [];
      inputFileArr.forEach((ele) => {
        let arr = [];
        if (typeof ele.value === "object") {
          //数组
          arr = _this.tempData(ele.value);
        } else {
          arr = _this.tempData([ele.value]);
        }
        resultInpurList = [...resultInpurList, ...arr];
      });

      this.inputFileList = resultInpurList;

      let outputFileArr = this.itemsOutputParam.filter(
        (ele) => ele.type.name === "file" || ele.type.name === "dir"
      );

      outputFileArr.forEach((ele) => {
        let arr = [];
        if (typeof ele.value === "object") {
          //数组
          arr = _this.tempData(ele.value);
        } else {
          arr = _this.tempData([ele.value]);
        }
        resultoutputList = [...resultoutputList, ...arr];
      });
      _this.outputFileList = resultoutputList;

      this.$bus.$emit("fileList", _this.inputFileList, _this.outputFileList);

    },

    tempData(data) {
      let suffix = ".tif;.tiff;.img;.dat;.geotiff;.shp";
      let resultInpurList = [];
      data.forEach((ele) => {
        if (typeof ele!=="string")return
        let aa = ele.split("/");
        let fileName = aa[aa.length - 1];
        let tempSuffix = ele.substring(ele.lastIndexOf(".")); //获取 .xxx
        if (suffix.indexOf(tempSuffix) != -1) {
          resultInpurList.push({ name: fileName, path: ele });
        }
      });

      return resultInpurList;
    },
    // 输入输出参数详情展示
    infomationShow(type) {
      this.infomationModalShow = true;
      if (type === "input") {
        this.paramInfomation.type = "输入";
        this.paramInfomation.content = JSON.parse(
          JSON.stringify(this.itemsInputParam)
        );
      } else if (type === "output") {
        this.paramInfomation.type = "输出";
        this.paramInfomation.content = JSON.parse(
          JSON.stringify(this.itemsOutputParam)
        );
      }
    },

    mousedownEvent: function (event, id) {
      this.drag = document.getElementById(id);
      var event = event || window.event; //兼容IE浏览器
      //    鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
      this.diffX = event.clientX - this.drag.offsetLeft;
      this.diffY = event.clientY - this.drag.offsetTop;
      if (typeof this.drag.setCapture !== "undefined") {
        this.drag.setCapture();
      }
    },
    mousemoveEvent: function (event) {
      if (JSON.stringify(this.drag) === "{}") {
        return;
      }
      var that = this;
      var eventData = event;
      if (!this.timeout) {
        this.timeout = setTimeout(function () {
          that.timeout = null;
          var moveX = eventData.clientX - that.diffX;
          var moveY = eventData.clientY - that.diffY;
          if (moveX < 0) {
            moveX = 0;
          } else if (moveX > window.innerWidth - that.drag.offsetWidth) {
            moveX = window.innerWidth - that.drag.offsetWidth;
          }
          if (moveY < 0) {
            moveY = 0;
          } else if (moveY > window.innerHeight - that.drag.offsetHeight) {
            moveY = window.innerHeight - that.drag.offsetHeight;
          }
          that.drag.style.left = moveX + "px";
          that.drag.style.top = moveY + "px";
        }, 4);
      }
    },
    onmouseupEvent: function (event) {
      this.drag = {};
    },
    mouseout() {
      this.drag = {};
    },

    timerStart() {
      let _this = this;
      _this.timer = setInterval(function () {
        _this.getTaskjobData(_this.taskId);
      }, 40000); //40s
    },
    destroyed() {
      clearInterval(this.timer);
      this.timer = null;
    },
    getVendorId(event) {
      let tempdata = event.target.value; //获取option对应的value值
      this.pageSize = parseInt(tempdata);
    },

    displayProductionLineGraph() {},
    updateParam() {
      this.isDisabled = !this.isDisabled;
      this.saveBtnShow = !this.saveBtnShow;
    },

    operatingDetails() {
      this.showOperatingDetailsModel = true;
      this.showParameterDetailsModel = false;
      this.showLogDetails = false;
      // this.getTaskjobData(this.taskId);
    },

    parameterDetails() {
      //参数设置
      this.showOperatingDetailsModel = false;
      this.showParameterDetailsModel = true;
      this.showLogDetails = false;
      this.isDisabled = true; //不能编辑
      this.saveBtnShow = false;
      this.getData(this.taskId);
    },

    openParameterDetails() {

      this.$parent.$refs.mapCompereDetal.openChange();
      this.getData(this.taskId);

    },
    offOperatingDetails() {
      this.showOperatingDetailsModel = false;
      console.log(this.taskId,'kkkk');
      console.log(this.workflowId,'kkk');
    },
    offParameterDetails() {
      this.showParameterDetailsModel = false;
    },
    offLogDetails() {
      this.showLogDetails = false;
    },
    // 查询工作流运行信息
    searchMassage() {
      let startWorkflowId = this.taskId;
      let params = {
        statusList: this.taskStatus,
      };
      let path =
        this.$api.taskManageApi.childTaskWorkFlow +
        startWorkflowId +
        "/running";

      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.length === 0) {
            this.itemsDetail = [];
          } else {
            let data = res.data.data;
            let getData = [];
            for (var i = 0; i < data.length; i++) {
              let temp = {};
              temp.name = data[i].label;
              temp.startTime = data[i].startTime;
              temp.updateTime = data[i].ms;

              getData.push(temp);
            }
            this.itemsDetail = getData;
          }
        }
      });
    },
    tasklogOk() {
      this.tasklogModal = !this.tasklogModal;
    },
    //任务详情
    getTaskjobData(taskId) {
      this.algoStatus = "";
      let self = this;
      let path =
        this.$api.taskManageApi.task +
        taskId +
        "/k8jobs/" +
        self.currentPage +
        "/" +
        self.pageSize;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.length === 0) {
            this.itemsDetail = [];
          } else {
            let data = res.data.data.list;
            let getData = [];
            for (var i = 0; i < data.length; i++) {
              let temp = {};
              temp.name = data[i].workflowTaskName;
              //时间截取 去掉年份
              let createT = data[i].startTime;
              console.log(createT,'开始时间')
              let endT = data[i].endTime;
              temp.startTime = createT.substring(5, createT.length);
              temp.endTime = endT.substring(5, endT.length);

              temp.algJobId = data[i].jobId;
              temp.status = data[i].status;
              temp.nodeName = data[i].nodeName;
              temp.identity = data[i].identity;
              temp.progress = data[i].progress;
              getData.push(temp); //每一行执行操作后房间getData里
            }

            this.itemsDetail = getData;
            console.log(this.itemsDetail,'任务详情数据');
            self.allNum = res.data.data.total;
            self.total = Math.ceil(res.data.data.total / self.pageSize);
          }
        }
      });
    },

    getTaskDetailLog(taskId, item) {
      this.tasklogModal = true;
      let self = this;
      // let url = window.location.href;
      // let arr = url.split("/");
      // let info = arr[arr.length - 3];
      // jobId能唯一标识哪个算法的日志
      console.log(item,"表格数据");
      let path =
        self.$api.taskManageApi.loglist +
        "?jobId=" +
        item.algJobId +
        "&pageSize=10000&page=1";
      this.http.get(path).then((res) => {
        if (res.data.code === 0) {
          let logData = res.data.data.log;
          let newlogArr = [];

          for (let i = 0; i < logData.length; i++) {
            let log = {};
            let dataContent = logData[i].content;
            let dataTime = logData[i].time;
            var dateee = new Date(dataTime).toJSON();
            let newDate = new Date(new Date(dateee))
              .toISOString()
              .replace(/T/g, " ")
              .replace(/\.[\d]{3}Z/, "");
            let consoleLog = newDate + "\xa0\xa0\xa0\xa0" + dataContent;
            log.logConsole = consoleLog;
            log.time = logData[i].time;
            newlogArr.push(log);
          }

          self.logConsole = newlogArr;
          self.logList = newlogArr;
        }
      });
    },



    //参数设置
    getData(taskId) {
      let path =
        this.$api.taskManageApi.getParamsPath + taskId + "/running/param";
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          let data = res.data.data;
          this.itemsInputParam = this.getFormatParam(data.inputParam);
          this.itemsInputParam.forEach((ele) => {
            if (
              (ele.type.name.toLowerCase() === "double" ||
                ele.type.name.toLowerCase() === "float" ||
                ele.type.name.toLowerCase() === "int") &&
              ele.value
            ) {
              ele.value = Number(ele.value);
            }

            if (ele.type.name.toLowerCase() === "json_object") {
              if (ele.value instanceof Object == true)
                ele.value = JSON.stringify(ele.value);
            }
            if (ele.type.name.toLowerCase() === "project_image") {
              //新增的类型project_image
              if (ele.value != null && ele.value instanceof Array == true)
                ele.value = JSON.stringify(ele.value); //转换为字符串
            }

            // 处理特殊下拉
            this.commonBeforeRender(ele)
          });

          let outData = this.getFormatParam(data.outputParam);
          outData.forEach((element) => {
            if (element.value == null) {
              element.value = [];
              element.value.push("无");
            }
            if (this.isArrayFn(element.value) && element.value.length < 1) {
              element.value.push("无");
            }
            if (!this.isArrayFn(element.value)) {
              let valueItem = element.value.toString();
              let tempValue = valueItem.split(/[,;]/);
              element.value = "";
              element.value = [];
              tempValue.forEach((ele) => {
                element.value.push(ele);
              });
            }

            // 处理特殊下拉
            this.commonBeforeRender(element)
          });
          this.itemsOutputParam = outData;
          this.openFileListModal(true);
        }
      });
    },
    isArrayFn(value) {
      if (typeof Array.isArray === "function") {
        return Array.isArray(value);
      } else {
        return Object.prototype.toString.call(value) === "[object Array]";
      }
    },
    getFormatParam(data) {
      let resultData = [];
      for (let i = 0; i < data.length; i++) {
        let tempInfo = data[i];
        let type = tempInfo.type.name.toLowerCase();
        let enumInfo = tempInfo.constraint;
        let enumObjArr = [];

        if (type === "select") {
          if (enumInfo === undefined) {
            console.warn("获取【" + tempInfo.label + "】参数失败");
            continue;
          }
          enumInfo = tempInfo.constraint.values;
          for (var key in enumInfo) {
            let newObj = new Object();
            newObj.label = key;
            newObj.value = enumInfo[key];
            enumObjArr.push(newObj);
          }
          delete tempInfo.constraint;
          tempInfo.constraint = enumObjArr;
        }
        resultData.push(tempInfo);
      }
      return resultData;
    },
    save() {
      let data = this.itemsInputParam;
      let param = new Object();
      let tempValue = "";
      // let isBatch = this.isBatch;
      // let interval = "#TASK#";
      // if (isBatch) interval = "#HT#";

      let path = this.$api.taskManageApi.getParamsPath + this.taskId + "/param";

      for (let i = 0; i < data.length; i++) {
        let tempInfo = data[i];
        let key = tempInfo.name;
        let value = tempInfo.value;
        let typeName = tempInfo.type.name.toLowerCase();
        let type = ["dem_select", "ref_select"];
        if (this.isArrayFn(value)) {
          param[key] = value;
          continue;
        }
        if (typeName == "file" || typeName == "dir") {
          if (tempInfo.type.plural) {
            tempValue = [];
            value = value.split(/,|;|#TASK#|#HT#/);
            value.forEach((element) => {
              tempValue.push(element);
            });
            param[key] = tempValue;
          } else {
            param[key] = value;
          }
        } else if (tempInfo.type.name.toLowerCase() === "project_image") {
          param[key] = JSON.parse(tempInfo.value); //再转换为对象
        } else if (type.indexOf(typeName) != -1) {
          param[key] = value ? value.split(/,|;|#TASK#|#HT#/) : [];
        } else if (typeName == "base_index_select") {
          param[key] = value ? value.split(/,|;|#TASK#|#HT#/)[0] : []; //索引只能有一个文件
        } else param[key] = value;
      }

      this.http.post(path, param).then((res) => {
        if (res.data.code == 0) {
          this.$Message.success("保存成功,请点击重试！");
        } else {
          this.$Message.error("保存失败:" + res.data.message);
        }
      });
      this.showParameterDetailsModel = false;
    },
    //////////////////////////////////以下为目录浏览功能//////////////////////////////////
    //文件浏览功能
    browserFile(item) {
      let _this = this;
      _this.currentItem = item;
      _this.fileCatalogModal = true;
      _this.$refs.refFileCatalogModal.initFileTree(item);
    },
    browserRef(item) {
      let _this = this;
      _this.spatialRefManageModal = true;
      _this.currentItem = item;
      _this.$refs.refSpatialRefManageModal.initRefTree(item);
    },
    fileCatalogModalOk(data) {
      this.fileCatalogModal = false;
      let path = data;
      let type = ["dem_select", "ref_select"];
      let typeName = this.currentItem.type.name.toLowerCase();
      if (type.indexOf(typeName) != -1) {
        path = data ? data.split(/,|;|#TASK#|#HT#/) : [];
      } else if (typeName == "base_index_select") {
        path = data ? data.split(/,|;|#TASK#|#HT#/)[0] : []; //索引只能有一个文件
      }
      this.currentItem.value = path;
    },
    fileCatalogModalClose() {
      this.fileCatalogModal = false;
    },
    spatialRefManageModalOk(data) {
      this.spatialRefManageModal = false;
      this.currentItem.value = data;
    },
    spatialRefManageModalClose() {
      this.spatialRefManageModal = false;
    },
    //////////////////////////////////以上文件浏览功能//////////////////////////////////

    // 获取DEM的下拉选项  // 注意：数据是从DEM列表接口获取，如果列表中pId数据发生变化是无法获取结果
    //基本参数和算法参数的特殊处理
    commonBeforeRender(tempValue) {

      // dem_select：用于选择dem数据，值为数组格式
      // ref_select：用于选择参考影像，值为数组格式；
      // base_index_select：用于选择基准索引，值为字符串file类型 不是数组；
      let nameType = tempValue.type.name.toLowerCase();
      if (nameType.indexOf("dem_select") != -1 ||
          nameType.indexOf("base_index_select") != -1 ||
          nameType.indexOf("ref_select") != -1) {
         this.getDemOptions(tempValue, tempValue.type.name);
      }
    },
    getDemOptions(item, type) {
      let path = this.$api.processingApi.getDemType;
      let param = {code: type };  //根据dem类型查对应的服务数据
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0 && res.data.success) {
          let options = [];
          let demArr = res.data.data;
          if (!demArr.length) return;
          demArr.forEach((ele) => {
            options.push({ label: ele.path[0], value: ele.path[0] });
          });

          this.$set(item.constraint,"values",options)
         // item.constraint.values = options;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },


  },
  components: {
    FileCatalog,
    SpatialReferenceManage,
  },
};
</script>
<!--css样式-->
<style lang='scss' scoped>
.tempstyle {
  z-index: 111;
  position: relative;
  display: grid;
  justify-content: center;
  margin-top: 110px;
}

.tempsstyles {
  position: fixed; // absolute;
  right: 60px;
  top: 158px; //60px;

  width: 850px;
  height: 530px;

  display: inline-block;
  border: 1px solid #d8dbe0;
  border-radius: 3px;
  background: rgb(255, 255, 255);
  box-shadow: 1px 1px 6px 6px rgba(0, 0, 0, 0.1);
}
span {
  font-size: 1rem;
  cursor: pointer;
}
.imagestyle {
  border-style: none;
  margin-left: -12px;
  vertical-align: middle;
}
#div1 {
  margin-top: 2px;
  margin-bottom: 2px;
  width: 100%;
  border-bottom: 1px solid #d8dbe0;
}
.inputRadio {
  width: 600px;
}
.table-responsive {
  display: block;
  overflow-x: scroll;
  -webkit-overflow-scrolling: touch;
  overflow-y: auto !important;
  height: 401px !important;
}
.taskTableStyle {
  margin-left: 10px;
  margin-right: 10px;
  text-align: center;
  height: 100%;
}

.body {
  width: 100%;
  margin: 15px 0px;
  padding: 0px 10px;
  height: 72%;
}

.close {
  position: absolute;
  right: 10px;
}
.bodyStyle {
  height: 76%;
  overflow-x: hidden;
  width: 100%;
  margin-top: 15px;
}
.titleTable {
  margin: 10px;
}
.inputTable {
  width: 97%;
  margin-left: 10px;
}
.outputTable {
  width: 97%;
  margin-left: 10px;
  margin-top: 20px;
}
.labelName {
  width: 15%;
  margin-right: 2%;
  margin-bottom: 5px;
}
.taskTableStyle {
  margin: 0 auto;
  border: 1px solid #c4c9d0;
  max-width: 100%;
}
.taskTableStyle > tr > td {
  /* width: 150px; */
  height: 40px;
  text-align: center;
}
.title,
.logTitle,
.parameter {
  /* margin-left: 10px; */
  font-weight: bold;
}
.logContent {
  height: 100%;
  max-width: 100%;
}
::-webkit-scrollbar-thumb {
  background-color: #7eb8ee;
}
::-webkit-scrollbar {
  // width: 6px;
  // height: 3px;
  background-color: #d8d8d8;
}
.okButton {
  height: 33px;
  margin-top: -6px;
}
.lastbtns {
  background-color: #6d6d6d !important ;
  color: #fff;
}
.modal-footer {
  height: 38px;
  position: absolute;
  border-top: 0;
  right: 9px;
  bottom: 10px;
}

.taskTableStyle td {
  padding: 0;
  vertical-align: middle;
}
.showParameterDetailsModel .table th,
.showParameterDetailsModel .table td {
  padding: 0.75rem;
  width: 700px;
  word-break: break-all;
}
.table .theade {
  background-color: #d8d8d8;
}
.ivu-table th {
  background: rgba(241, 244, 249, 1);
  height: 50px;
}
.inputData {
  margin-left: 10px;
  padding-left: 10px;
  border-left: 8px solid #3c6ef0;
}
.table {
  width: 99% !important;
}

.inputTd {
  float: left;
  width: 94%;
  margin-bottom: 0px;
}
.inputTd1 {
  float: left;
  width: 718px; // 94%;
  margin-bottom: 0px;
  background: #f5f5f5;
  // padding: 10px 4px 10 15px;
  border: 1px solid #d8dbe0;
  border-radius: 0.25rem;

  max-height: 150px;
  overflow-y: auto;
}
.inputTd2 {
  float: left;
  width: 718px; // 94%;
  margin-bottom: 0px;
  max-height: 150px;
  overflow-y: auto;
}

.btnBrowser {
  float: right;
  margin-top: 3px;
  margin-left: 10px;
}

.btn-info {
  height: 32px !important;
}
.taskTitle {
  padding: 15px 10px 10px 10px;
}

/**目录浏览 */
.optiostyle {
  height: 40px;
  width: 370px;
  float: right;
  font-size: 1rem;
  font-weight: bold;
  z-index: 99;
  margin-top: -50px;
}
.saveFileStyle {
  width: 280px;
}
.treeDiv {
  height: 500px;
  width: 760px;
  overflow-y: auto;
}
.treeDiv1 {
  height: 300px;
  width: 300px;
  overflow-y: auto;
}
.suffixBtn {
  margin-left: 10px;
}
.selectSuffix {
  float: left;
  width: 80%;
}

.page-link {
  cursor: pointer;
}
.pageContent {
  margin-right: 26px;
  font-size: 14px;
}
.selectStyle {
  display: inline-block;
  width: 100px;
  margin-right: 5px;
}
.footerPage {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
  color: black;
}

.liClass {
  color: #768192;
  list-style: none;
  padding: 6px 12px;
}
.liClass:hover {
  color: black;
}
.zZindex {
  z-index: 3000 !important;
  width: 300px;
  height: 400px;
}

.mainBtn {
  width: 40px;
  margin-top: 10px;
}
</style>

<style scoped>
/deep/.ivu-table-body {
  /* height: calc(30vh); */
  overflow-y: auto;
  overflow-x: hidden;
}
/deep/ .ivu-table-row .ivu-table-column-eDLGrL .ivu-table-cell {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.info-pre {
  height: 25rem;
  width: 780px;
  margin-bottom: -11px;
}
.myColPri {
  display: inline-block;
  margin-bottom: 0;
}
</style>
